package cn.hejiang.mamis.core.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import cn.hejiang.mamis.core.dto.AmisCrudDTO;
import cn.hejiang.mamis.core.dto.ResultDTO;
import cn.hejiang.mamis.core.entity.PlatUser;
import cn.hejiang.mamis.core.entity.SessionDetails;
import cn.hejiang.mamis.core.entity.SysMenu;
import cn.hejiang.mamis.core.entity.SysRole;
import cn.hejiang.mamis.core.service.ContextService;
import cn.hejiang.mamis.core.service.impl.SysRoleServiceImpl;
import cn.hejiang.mamis.core.util.EntityUtil;
import cn.hejiang.mamis.core.util.QueryUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@RequestMapping("/mamis/sys/role")
@RestController
@Slf4j
public class SysRoleController {
	@Autowired
	ContextService contextService;

	@Autowired
	SysRoleServiceImpl sysRoleService;

	@GetMapping("/list")
	public ResultDTO<AmisCrudDTO<SysRole>> getDeptRoleList(final HttpServletRequest request,
			@RequestParam("deptId") String deptId) {
		// 因为前端传递问题，空白表示为空
		if (StrUtil.equals(deptId, "root")) {
			deptId = null;
		}

		// 查询数据库
		List<SysRole> list = sysRoleService.getDeptRoleList(deptId, contextService.getSystem().getId());

		// 构造 amis 要求的数据结构
		final AmisCrudDTO<SysRole> data = new AmisCrudDTO<>();
		data.setItems(list);

		// 返回结果集
		return ResultDTO.success(data);
	}

	@PostMapping()
	public ResultDTO saveDeptRole(final HttpServletRequest request, @RequestBody final SysRole obj) {
		final SessionDetails session = contextService.getSession(request);

		// 因为前端传递问题，空白表示为空
		if (StrUtil.equals(obj.getDeptId(), "root")) {
			obj.setDeptId(null);
		}

		// 清除不可更新字段
		obj.setDeleted(null);
		obj.setOwnSysId(null);
		obj.setOwnDeptId(null);
		obj.setCreatedAt(null);
		obj.setCreatedBy(null);
		obj.setUpdatedAt(null);
		obj.setUpdatedBy(session.getCurUserId());

		boolean ret;
		if (StrUtil.isNotBlank(obj.getId())) {
			// update
			UpdateWrapper<SysRole> updater = QueryUtil.newUpdateWrapper(obj.getId());
			ret = sysRoleService.update(obj, updater);
		} else {
			// insert
			obj.setId(null);
			obj.setCreatedBy(session.getCurUserId());
			obj.setOwnSysId(contextService.getSystem().getId());
			ret = sysRoleService.save(obj);
		}

		return ret ? ResultDTO.success() : ResultDTO.error("保存失败");
	}

	@DeleteMapping("/{id}")
	public ResultDTO delDeptRole(final HttpServletRequest request, @PathVariable("id") String id) {
		UpdateWrapper<SysRole> updater = QueryUtil.newDeleteWrapper(id);
		boolean ret = sysRoleService.update(null, updater);

		return ret ? ResultDTO.success() : ResultDTO.error("删除失败");
	}

	@GetMapping("/user/list")
	public ResultDTO<AmisCrudDTO<PlatUser>> getRoleUserList(final HttpServletRequest request,
			@RequestParam("roleId") String roleId) {
		// 查询数据库
		List<PlatUser> list = sysRoleService.getRoleUserList(roleId, contextService.getSystem().getId());

		// 构造 amis 要求的数据结构
		final AmisCrudDTO<PlatUser> data = new AmisCrudDTO<>();
		data.setItems(list);

		// 返回结果集
		return ResultDTO.success(data);
	}

	@GetMapping("/user/candidates")
	public ResultDTO<AmisCrudDTO<PlatUser>> getRoleUserCandidates(final HttpServletRequest request,
			@RequestParam("roleId") String roleId) {
		// 查询数据库
		List<PlatUser> list = sysRoleService.getRoleUserCandidates(roleId, contextService.getSystem().getId());

		// 构造 amis 要求的数据结构
		final AmisCrudDTO<PlatUser> data = new AmisCrudDTO<>();
		data.setItems(list);

		// 返回结果集
		return ResultDTO.success(data);
	}

	@PostMapping("/user")
	public ResultDTO addRoleUsers(final HttpServletRequest request, @RequestBody Map<String, String> data,
			@RequestParam("roleId") String roleId) {
		final SessionDetails session = contextService.getSession(request);

		String[] ids = data.get("userIds").split(",");

		int ret = 0;
		for (String id : ids) {
			ret += sysRoleService.addRoleUser(roleId, id, contextService.getSystem().getId(), session.getCurUserId());
		}

		return ret > 0 ? ResultDTO.success() : ResultDTO.error("保存失败");
	}

	@DeleteMapping("/user/{userId}")
	public ResultDTO delRoleUser(final HttpServletRequest request, @RequestParam("roleId") String roleId,
			@PathVariable("userId") String userId) {
		int ret = sysRoleService.delRoleUser(roleId, userId, contextService.getSystem().getId());

		return ret > 0 ? ResultDTO.success() : ResultDTO.error("删除失败");
	}

	@GetMapping("/menu/option")
	public ResultDTO<Map<String, String>> getRoleMenuOption(final HttpServletRequest request,
			@RequestParam("roleId") String roleId) {
		List<SysMenu> menuList = sysRoleService.getRoleMenuList(roleId, contextService.getSystem().getId());
		List<SysMenu> menuTree = EntityUtil.plainToTree(menuList);

		List<String> pathList = EntityUtil.toOptionPathList(menuTree);
		Map<String, String> data = new HashMap<>();
		data.put("menuTree", StrUtil.join(",", pathList));

		return ResultDTO.success(data);
	}

	@PostMapping("/menu/option")
	public ResultDTO saveRoleMenuOption(final HttpServletRequest request, @RequestBody Map<String, String> data,
			@RequestParam("roleId") String roleId) {
		final SessionDetails session = contextService.getSession(request);

		Set<String> menuIdSet = new HashSet<>();
		Arrays.asList(data.get("menuTree").split(",")).forEach(i -> {
			Arrays.asList(i.split("/")).forEach(menuIdSet::add);
		});

		int ret = sysRoleService.saveRoleMenus(roleId, menuIdSet, contextService.getSystem().getId(),
				session.getCurUserId());

		return ret > 0 ? ResultDTO.success() : ResultDTO.error("保存角色菜单失败");
	}
}
